package cn.walls1717.ggkt.order.api;

import cn.walls1717.ggkt.exception.MyException;
import cn.walls1717.ggkt.order.service.OrderInfoService;
import cn.walls1717.ggkt.order.service.WxPayService;
import cn.walls1717.ggkt.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 前台微信支付相关接口
 *
 * @author walls1717
 * @since 2022/7/22
 **/
@Api(tags = "前台微信支付相关接口")
@Slf4j
@RestController
@RequestMapping("/api/order/wxPay")
public class WxPayController {

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private OrderInfoService orderInfoService;

    @ApiOperation("下单小程序支付")
    @GetMapping("/createJsapi/{orderNo}")
    public Result<Map<String, String>> createJsapi(@PathVariable("orderNo") String orderNo) {
        return Result.success(wxPayService.createJsapi(orderNo));
    }

    @ApiOperation("查询支付状态")
    @GetMapping("/queryPayStatus/{orderNo}")
    public Result<?> queryPayStatus(@PathVariable("orderNo") String orderNo) {
        // 支付成功返回值
        String success = "SUCCESS";
        // 获取支付是否成功，如果成功则对应为SUCCESS
        String tradeState = "trade_state";
        log.info("orderNo:{}", orderNo);
        //调用查询接口
        Map<String, String> resultMap = wxPayService.queryPayStatus(orderNo);
        //出错
        if (resultMap == null) {
            throw new MyException(20001, "支付出错");
        }
        //如果成功
        if (success.equals(resultMap.get(tradeState))) {
            //更改订单状态，处理支付结果
            String outTradeNo = resultMap.get("out_trade_no");
            log.info("out_trade_no:{}", outTradeNo);
            orderInfoService.updateOrderStatus(outTradeNo);
            return Result.success().message("支付成功");
        }
        return Result.success().message("支付中");
    }
}
